package logic

import (
	"an_ju_ke/models"
	"context"
	"fmt"

	"an_ju_ke/myrpc/internal/svc"
	"an_ju_ke/myrpc/myrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *myrpc.LoginRequest) (*myrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	key := fmt.Sprintf("image_captcha_user_name:%s", in.UserName)
	get, _ := models.Rdb.Get(models.Ctx, key).Result()
	if get != in.Code {
		return nil, fmt.Errorf("验证码错误")
	}
	if models.DB.Where("user_name = ?", in.UserName).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if user.UserPassword != in.UserPassword {
		return nil, fmt.Errorf("密码错误")
	}
	models.Rdb.Del(models.Ctx, key)
	return &myrpc.LoginResponse{}, nil
}
